WorkerScript.onMessage = function(message) {
    doLoadSpots(message, true);
}


function doLoadSpots(message, withGeo) {
    var xhr = new XMLHttpRequest;
    var url = message.g.serverAPI + "poi/suggested?details=true&stats=true&per_page=" + message.g.perPage + "&oauth_token=" + message.g.token;

    if (message.search != undefined && message.search != "") {
        url += "&text=" + message.search
    }
    if (withGeo && message.g.latitude != 0) {
        url += "&geo=" + message.g.latitude + "," + message.g.longitude;
    }

    xhr.open("GET", url);
    //console.log("URL: " + url)
    xhr.onreadystatechange = function() {
        try {
            if (xhr.readyState == XMLHttpRequest.DONE) {
                message.model.clear();
                message.model.sync();
                //console.log("RESPONSE: " + xhr.responseText)
                var response = JSON.parse(xhr.responseText);
                if (response.data.length != 0 || !withGeo) {
                    for (var i in response.data) {
                        var spot = response.data[i].poi;

                        message.model.append({
                                      spotName: spot.name,
                                      spotInCollection: spot.stats.own_book,
                                      spotId: spot.id,
                                      spotTags: spot.tag_list != null ? spot.tag_list : "",
                                      spotCity: spot.city,
                                      spotRegion: spot.region,
                                      spotCountry: spot.country,
                                      spotStreet: spot.street
                        });
                    }
                    message.model.sync();
                    WorkerScript.sendMessage({ 'result': 'SUCCESS' })
                } else {
                    doLoadSpots(message, false)
                }
            }
        } catch(err) {
            WorkerScript.sendMessage({ 'result': 'FAILURE', 'message': err + ", " + xhr.responseText });
        }

    }
    xhr.send();
}
